# {
#   "page": 1,
#   "size": 10,
#   "keyword": "姜文",
#   "resetPage": true,
#   "channelId": null,
#   "status": 9,
#   "beginPubDate": null,
#   "endPubDate": null
# }
# http://localhost:8802/wemedia/MEDIA/wemedia/api/v1/news/list
# 请求方法
# POST
import time
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

from page.basepage import BasePage
from selenium.webdriver.common.by import By


class ArticleListPage(BasePage):
    def __init__(self,driver):
        super().__init__(driver)
        self.list_page = (By.XPATH, '//span[text()="内容列表"]')
        self.keyword_input = (By.CSS_SELECTOR,'input[placeholder="请输入关键字"]')
        self.next_page = (By.CSS_SELECTOR,'.btn-next')
        self.page_size = (By.CSS_SELECTOR,'.el-select-dropdown__item.selected')
        self.cur_page = (By.CSS_SELECTOR,'.number.active')
        # self.pre_page = (By.CSS_SELECTOR,'.el-icon.el-icon-arrow-left')
        self.pre_page = (By.CSS_SELECTOR,'.btn-prev')
        self.total = (By.CSS_SELECTOR,'.el-pagination__total')
        self.maxPage = (By.CSS_SELECTOR,'input[type="number"]')
        self.body = (By.TAG_NAME, "body")
        self.first_article_title_el = (By.CSS_SELECTOR, ".article-title")
        self.dropdown_channel = (By.CSS_SELECTOR, '.el-input__inner[readonly]')
        self.get_channel = (By.XPATH, "//li[@class='el-select-dropdown__item']/span")
        self.status_text_el = (By.XPATH, './/div[@class="bottom"]//span')
        self.page_num_el = (By.CSS_SELECTOR, '.el-pager .number.active')
        self.buttom_page_size = (By.CSS_SELECTOR, '.el-input.el-input--mini.el-input--suffix')
        self.buttom_page_size_text = (By.CSS_SELECTOR,'ul.el-select-dropdown__list li.selected span')
        self.page_size_dropdown = (By.CSS_SELECTOR, '.el-select-dropdown')

    def goto_list_page(self):
        WebDriverWait(self.driver, 10).until_not(
            EC.presence_of_element_located(
                (By.CSS_SELECTOR, ".el-loading-mask.is-fullscreen")
            )
        )
        self.click(self.list_page)


    def goto_next_page(self):
        nextPage = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.next_page)
        )
        nextPage.click()

    def goto_pre_page(self):
        nextPage = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.pre_page)
        )
        nextPage.click()

    def get_pre_btn_status(self):
        prebtn = self.find(self.pre_page)
        return prebtn.get_attribute("disabled")

    def get_next_btn_status(self):
        prebtn = self.find(self.next_page)
        return prebtn.get_attribute("disabled")

    def get_max_page(self):
        maxp = self.find(self.maxPage)
        return int(maxp.get_attribute('max'))

    def set_page_num(self,num):
        pageNum = self.find(self.maxPage)
        pageNum.send_keys(num)
        self.click(self.body)

    def set_keyword(self,keyword):
        keyword_el = self.find(self.keyword_input)
        keyword_el.clear()
        keyword_el.send_keys(keyword)
        self.click(self.body)

    def get_total(self):
        total_el = self.find(self.total)
        import re
        # print("total_el.text = ",total_el.text)
        total = re.search(r'\d+', total_el.text)
        return int(total.group())

    def get_first_article_title(self):
        title_elem = self.find(self.first_article_title_el)
        return title_elem.text.strip()

    def get_current_page_index(self):
        pageindex = self.find(self.cur_page)
        return pageindex.text.strip()

    def choose_status(self,status):
        status_button = (By.XPATH, f'//span[@class="el-radio__label" and contains(text(), "{status}")]')
        self.click(status_button)
        time.sleep(1)

    def select_channel(self, channel_name):
        time.sleep(1)
        dropdown_input = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(self.dropdown_channel)
        )
        dropdown_input.click()
        time.sleep(1)
        # 先获取所有频道元素
        options = WebDriverWait(self.driver, 10).until(
            EC.presence_of_all_elements_located(self.get_channel)
        )

        # 找到目标频道的位置（索引+1，因为列表索引是0开始）
        target_index = None
        for idx, opt in enumerate(options, start=1):
            # print("opt.text.strip() = ",opt.text.strip())
            if opt.text.strip() == channel_name:
                target_index = idx
                break

        if target_index is None:
            raise ValueError(f"频道 '{channel_name}' 不存在")

        # print(f"频道 '{channel_name}' 是第 {target_index} 个")

        # 点击目标频道
        options[target_index - 1].click()
        return target_index-5

    def get_article_info_by_index(self, index):
        """
        index: 第几条文章，从 1 开始
        返回 (标题, 发表状态, 审核状态)
        """
        self.click(self.list_page)
        try:
            card = WebDriverWait(self.driver, 10).until(
                EC.element_to_be_clickable((By.CSS_SELECTOR, f".item-card:nth-child({index})"))
            )
        except:
            # 10 秒后还没有任何结果，认为是空列表
            return None, None
        title = card.find_element(By.CSS_SELECTOR, ".center").text
        # publish = card.find_elements(By.CSS_SELECTOR, ".publish")
        # publish = publish[0].text if publish else ""
        # audit = card.find_element(By.CSS_SELECTOR, ".audit").text
        # 2. 在卡片内部再查 .bottom 区域里的所有 span

        status_spans = card.find_elements(*self.status_text_el)
        status_text = ' '.join(span.text for span in status_spans)
        return title, status_text

    def get_current_page_num(self):
        # 返回当前页码，注意需要处理转换为 int
        page_el = self.find(self.page_num_el)
        return int(page_el.text.strip())




    def get_current_page_size_num(self):
        # 1. 点击下拉框，让列表出现
        time.sleep(1)
        size_selector = self.find(self.buttom_page_size)

        size_selector.click()
        time.sleep(1)
        # 2. 等待下拉列表渲染，再读“已选中”的文本
        selected_span = WebDriverWait(self.driver, 10).until(
            EC.presence_of_element_located(
                self.buttom_page_size_text
            )
        )
        import re
        page_size = int(re.search(r'\d+', selected_span.text.strip()).group())
        return page_size

    def select_page_size(self, size_text):
        """
        size_text: "10条/页" | "20条/页" ... | "100条/页"
        """
        time.sleep(1)
        # 1. 点下拉框
        size_selector = self.find(self.buttom_page_size)
        size_selector.click()
        time.sleep(1)

        # 2. 等列表出现，再点目标选项
        target = WebDriverWait(self.driver, 10).until(
            EC.element_to_be_clickable(
                (By.XPATH,
                 f'//span[contains(text(),"{size_text}")]')  # ✅ 正确写法
            )
        )
        target.click()
        time.sleep(5)

        # 3. 可选：等下拉消失
        WebDriverWait(self.driver, 10).until(
            EC.invisibility_of_element_located(
                self.page_size_dropdown
            )
        )

    def get_article_all_page_info(self):
        """
        index: 第几条文章，从 1 开始
        返回 (标题, 发表状态, 审核状态)
        """
        self.click(self.list_page)
        time.sleep(1)
        cards = self.driver.find_elements(By.CSS_SELECTOR, ".item-card")
        listInfo = []
        for card in cards:
            title = card.find_element(By.CSS_SELECTOR, ".center").text
            publish = card.find_elements(By.CSS_SELECTOR, ".publish")
            publish = publish[0].text if publish else ""
            audit = card.find_elements(By.CSS_SELECTOR, ".audit")
            audit = audit[0].text if audit else ""
            listInfo.append([title, publish, audit])

        return listInfo

